package com.fingard.dsp.bank.directbank.boc01;

import com.fingard.dsp.bank.directbank.bankInterface.IBalanceCheck;
import com.fingard.dsp.bank.reqrespobj.balancecheck.ReqBalCheckQry;
import com.fingard.dsp.bank.reqrespobj.balancecheck.RetAtsBalCheckQry;
import com.fingard.dsp.bank.reqrespobj.balancecheck.detail.RetAtsBalCheckDetail;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileInputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.zip.GZIPInputStream;


/**
 * Created by F on 2017/6/6.
 */
public class BOC01BalanceCheck extends BOC01Base implements IBalanceCheck {
    //单个余额对账查询和批量余额对账查询，统一采用流处理方式
    //1、循环调用ReqBalCheckQry.readRecord()读取一个请求明细，然后写入发银行的XML对象
    //2、发银行
    //3、循环调用XmlTextReader.read()读取一个银行返回节点，赋值返回ATS的明细对象，
    //   然后调用RetAtsBalCheckQry.writeRetDetail()，写入返回ATS的明细
    //4.根据返回的对账单号，通过ftp协议，进行对账单的下载，然后财务自己比对数据
    @Override
    public RetAtsBalCheckQry d_7508_BalCheck(ReqBalCheckQry p_req7508) throws Exception {
        //余额对账查询返回ATS的对象
        RetAtsBalCheckQry retAts = new RetAtsBalCheckQry(p_req7508.reqHeader, p_req7508.actNum);
        retAts.writeStart();//写返回ATS的统一头部信息
        try {
            if(getBankConfig().getValueAsString("transCode").equals("b2e0077")) {
                BOC01Header bankHeader = new BOC01Header();
                bankHeader.trncod = "b2e0077";//账单核对
                bankHeader.trnid = getQryTransID();//报文编号 字母数字串 0-12位
                int begnum = 1;
                int intPageNumber = 35;
                XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
                //写入通用的头部节点
                writeCommonHeader(xmlWriter, bankHeader);
                xmlWriter.writeStartElement("trn-b2e0077-rq");
                xmlWriter.writeStartElement("b2e0077-rq");
                xmlWriter.writeElementString("ibknum", "");//对账年月 yyyyMM
                xmlWriter.writeElementString("actacn", p_req7508.actNum);
                xmlWriter.writeElementString("billdate", getBankConfig().getValueAsString("conagrno"));
                xmlWriter.writeElementString("begnum", String.valueOf(begnum));//是否需要分页查询
                xmlWriter.writeElementString("recnum", String.valueOf(intPageNumber));
                xmlWriter.writeEndElement();
                xmlWriter.writeEndElement();//trn-b2e0358-rq
                xmlWriter.writeEndDocument();
                String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());

                if (tmpStrRet[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();

                    XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);

                    if (tmpBkReader != null) {
                        String tmprspcod = tmpBkReader.getFirstText("/bocb2e/trans/trn-b2e0077-rs/status/rspcod");
                        String tmprspmsg = tmpBkReader.getFirstText("/bocb2e/trans/trn-b2e0077-rs/status/rspmsg");
                        if (isActiveRetCode(tmprspcod)) {
                            String totalnum = tmpBkReader.getFirstText("/bocb2e/trans/trn-b2e0077-rs/totalnum");//总笔数
                            String backnum = tmpBkReader.getFirstText("/bocb2e/trans/trn-b2e0077-rs/backnum");//返回记录数
                            String rspcod = tmpBkReader.getFirstText("/bocb2e/trans/trn-b2e0077-rs/b2e0077-rs/status/rspcod");
                            String rspmsg = tmpBkReader.getFirstText("/bocb2e/trans/trn-b2e0077-rs/b2e0077-rs/status/rspmsg>");

                            if (rspcod.equals("B001") || rspcod.equals("B002")) {
                                RetAtsBalCheckDetail tmpRetDetail = new RetAtsBalCheckDetail();
                                tmpRetDetail.actNum = tmpBkReader.getFirstText("/bocb2e/trans/trn-b2e0077-rs/b2e0077-rs/account/actacn");
                                tmpRetDetail.dateFrom = tmpBkReader.getFirstText("/bocb2e/trans/trn-b2e0077-rs/b2e0077-rs/datescope/from");
                                tmpRetDetail.dateTo = tmpBkReader.getFirstText("/bocb2e/trans/trn-b2e0077-rs/b2e0077-rs/datescope/to");
                                tmpRetDetail.respCode = "0";
                                tmpRetDetail.respInfo = rspmsg;
                                tmpRetDetail.statementNumber = tmpBkReader.getFirstText("/bocb2e/trans/trn-b2e0077-rs/b2e0077-rs/cdno");//对账单编号,取批次号?
                                //tmpRetDetail.acctType = "";//存款种类
                                tmpRetDetail.actCur = p_req7508.actCur;
                                tmpRetDetail.depositNo = tmpBkReader.getFirstText("/bocb2e/trans/trn-b2e0077-rs/b2e0077-rs/cdno");
                                ;//存单号码
                                tmpRetDetail.prcBrn = tmpBkReader.getFirstText("/bocb2e/trans/trn-b2e0077-rs/b2e0077-rs/billinfo/fatorg");
                                //银行都是按照月份返回的
                                String yearMonth = tmpRetDetail.dateFrom.replace("-", "").substring(0, 6);
                                tmpRetDetail.yearMonth = yearMonth;
                                tmpRetDetail.cltNbr = tmpBkReader.getFirstText("/bocb2e/trans/trn-b2e0077-rs/b2e0077-rs/cusid");
                                //tmpRetDetail.cdFlag = tmpBkReader.readedXElement.getSingleText("direction");
                                tmpRetDetail.iacNbr = p_req7508.actNum;
                                tmpRetDetail.ccyType = tmpBkReader.getFirstText("/bocb2e/trans/trn-b2e0077-rs/b2e0077-rs/account/acctype");
                                tmpRetDetail.actBrn = tmpBkReader.getFirstText("/bocb2e/trans/trn-b2e0077-rs/b2e0077-rs/billinfo/signedorg");
                                tmpRetDetail.prebal = tmpBkReader.getFirstText("/bocb2e/trans/trn-b2e0077-rs/b2e0077-rs/prebal");
                                tmpRetDetail.actBal = tmpBkReader.getFirstText("/bocb2e/trans/trn-b2e0077-rs/b2e0077-rs/lastbal");


                                //是否经过计算得出平或者不平
                                long prebal = Long.valueOf(tmpRetDetail.prebal);
                                while (tmpBkReader.read("/bocb2e/trans/trn-b2e0077-rs/b2e0077-rs/transinfo")) {
                                    String cdFlag = tmpBkReader.readedXElement.getSingleText("direction");
                                    long amount = 0L;
                                    if (cdFlag.equals("C")) {
                                        amount = Long.valueOf(tmpBkReader.readedXElement.getSingleText("creditamt").replace("-", "").replace("+", ""));
                                        prebal = prebal - amount;
                                    } else {
                                        amount = Long.valueOf(tmpBkReader.readedXElement.getSingleText("debitamt").replace("-", "").replace("+", ""));
                                        prebal = prebal + amount;
                                    }
                                }
                                String atsFlag = "";//2:平，3:不平，1:未对帐
                                if (prebal == Long.valueOf(tmpRetDetail.actBal)) {
                                    atsFlag = "2";
                                } else {
                                    atsFlag = "3";
                                }
                                tmpRetDetail.dzFlag = atsFlag;
                                String balDate = tmpBkReader.getFirstText("/bocb2e/trans/trn-b2e0077-rs/b2e0077-rs/billinfo/accdate");
                                if (balDate.length() == 8) {
                                    tmpRetDetail.balDate = balDate.substring(0, 4) + "-" + balDate.substring(4, 6) + "-" + balDate.substring(6, 8);
                                } else {
                                    tmpRetDetail.balDate = balDate;
                                }
                                tmpRetDetail.fixDate = tmpRetDetail.balDate;
                                retAts.writeRetDetail(tmpRetDetail);
                            } else {
                                retAts.writeRespCode("-1");
                                retAts.writeRespInfo(rspmsg);
                            }
                        } else {
                            retAts.writeRespCode("-1");
                            retAts.writeRespInfo(tmprspmsg);
                        }
                    } else {
                        retAts.writeRespCode("-1");
                        retAts.writeRespInfo(tmpSbMsg.toString());
                    }
                } else {
                    //模拟银行返回 只模拟返回到ATS  银行的无法模拟
                /*RetAtsBalCheckDetail tmpRetDetail = new RetAtsBalCheckDetail();
                tmpRetDetail.respCode = "0";
                tmpRetDetail.respInfo = "";
                tmpRetDetail.actNum = p_req7508.actNum;
                tmpRetDetail.statementNumber = p_req7508.reqHeader.transSeqID;//对账单编号
                tmpRetDetail.acctType = "2";//存款种类
                tmpRetDetail.actCur = "CNY";
                String dzFlag = "2";
                String atsFlag = "";
                if ("1".equals(dzFlag)) {
                    atsFlag = "2";
                } else if ("2".equals(dzFlag)) {
                    atsFlag = "3";
                } else {//默认（0）和未对账（3）
                    atsFlag = "1";
                }
                tmpRetDetail.dzFlag = atsFlag;
                tmpRetDetail.actName = "末账户";
                tmpRetDetail.actBal = "254.00";
                tmpRetDetail.amountIncurred = "456.00";
                retAts.writeRetDetail(tmpRetDetail);*/
                    retAts.writeRespCode("-1");
                    retAts.writeRespInfo(tmpStrRet[1]);
                }
            } else{
                trans_b2e0358(retAts,p_req7508);
            }
        } catch (Exception e) {
            retAts.writeRespCode("-1");
            retAts.writeRespInfo(e.getMessage());
            e.printStackTrace();
        }
        retAts.writeEnd();
        return retAts;
    }

    public void trans_b2e0358(RetAtsBalCheckQry retAts,ReqBalCheckQry p_req7508) throws Exception{

        BOC01Header bankHeader = new BOC01Header();
        bankHeader.trncod = "b2e0358";//账单核对
        bankHeader.trnid = getQryTransID();//报文编号 字母数字串 0-12位
        int begnum = 1;
        int intPageNumber = 35;
        XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
        //写入通用的头部节点
        writeCommonHeader(xmlWriter, bankHeader);
        xmlWriter.writeStartElement("trn-b2e0358-rq");
        xmlWriter.writeStartElement("b2e0358-rq");
        xmlWriter.writeElementString("checkmonth", p_req7508.yearMonth);//对账年月 yyyyMM
        xmlWriter.writeElementString("overdueflag", "");
        xmlWriter.writeElementString("conagrno", getBankConfig().getValueAsString("conagrno"));
        xmlWriter.writeElementString("begnum", String.valueOf(begnum));//是否需要分页查询
        xmlWriter.writeElementString("recnum", String.valueOf(intPageNumber));
        xmlWriter.writeEndElement();
        xmlWriter.writeEndElement();//trn-b2e0358-rq
        xmlWriter.writeEndDocument();
        String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());

        if (tmpStrRet[0].length() == 0) {
            StringBuilder tmpSbMsg = new StringBuilder();

            XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);

            if (tmpBkReader != null) {
                String tmprspcod = tmpBkReader.getFirstText("/bocb2e/trans/trn-b2e0358-rs/status/rspcod");
                String tmprspmsg = tmpBkReader.getFirstText("/bocb2e/trans/trn-b2e0358-rs/status/rspmsg");
                if (isActiveRetCode(tmprspcod)) {
                    String totalnum = tmpBkReader.getFirstText("/bocb2e/trans/trn-b2e0358-rs/totalnum");//总笔数
                    String backnum = tmpBkReader.getFirstText("/bocb2e/trans/trn-b2e0358-rs/backnum");//返回记录数
                    while (tmpBkReader.read("/bocb2e/trans/trn-b2e0358-rs/b2e0358-rs")) {
                        RetAtsBalCheckDetail tmpRetDetail = new RetAtsBalCheckDetail();
                        if (tmpBkReader.readedXElement.getSingleChild("status") != null) {
                            String tmpEachRspcod = tmpBkReader.readedXElement.getSingleChild("status").getSingleText("rspcod");
                            String tmpEachRspmsg = tmpBkReader.readedXElement.getSingleChild("status").getSingleText("rspmsg");
                            if (tmpEachRspcod.equals("B001"))//这个状态不知道有没有什么标志
                            {
                                tmpRetDetail.respCode = "0";
                                tmpRetDetail.statementNumber = tmpBkReader.readedXElement.getSingleText("stmtnum");
                                tmpRetDetail.dateFrom = tmpBkReader.readedXElement.getSingleText("checkmonth");
                                //批量写入之后根据对账单的号码对对账单进行下载，然后读取对账单的记录信息回传给ATS（对账单下载(b2e0359)）
                                BOC01Header bankHeaderDown = new BOC01Header();
                                bankHeaderDown.trncod = "b2e0359";//账单下载
                                bankHeaderDown.trnid = getQryTransID();
                                XmlTextWriter xmlWriterDown = new XmlTextWriter();//发银行报文的XML对象
                                //写入通用的头部节点
                                writeCommonHeader(xmlWriterDown, bankHeader);
                                xmlWriterDown.writeStartElement("trn-b2e0359-rq");
                                xmlWriterDown.writeStartElement("b2e0359-rq");
                                xmlWriterDown.writeElementString("insid", "");//客户的业务编号(不明确)
                                xmlWriterDown.writeElementString("stmtnum", tmpRetDetail.statementNumber);
                                xmlWriterDown.writeEndElement();
                                xmlWriterDown.writeEndElement();
                                xmlWriter.writeEndDocument();
//                                  跟银行明确一下是不是根据前置机自动访问ftp服务器下载
                                String[] tmpStrRet1 = sendToBank(xmlWriter.toXmlString());
                                if (tmpStrRet1[0].length() == 0) {
                                    StringBuilder tmpSbMsg1 = new StringBuilder();
                                    //解析银行返回
                                    XmlTextReader tmpBkReader1 = loadBankRespXmlReader(tmpStrRet1[1], tmpSbMsg1);
                                    if (tmpBkReader1 != null) {
                                        String tmprspcod1 = tmpBkReader1.getFirstText("/bocb2e/trans/trn-b2e0359-rs/status/rspcod");
                                        String tmprspmsg1 = tmpBkReader1.getFirstText("/bocb2e/trans/trn-b2e0359-rs/status/rspmsg");
                                        if (isActiveRetCode(tmprspcod1)) {
                                            while (tmpBkReader1.read("/bocb2e/trans/trn-b2e0359-rs/b2e0359-rs")) {
                                                //访问本机的共享目录文件
                                                String filePath = "";
                                                String fileName = tmpBkReader1.readedXElement.getSingleText("filename");
                                                InputStream inputStream = null;
                                                SmbFileInputStream in = null;
                                                Scanner sc = null;
                                                try {
                                                    String userName = bankFront.userName;
                                                    String userPassword = bankFront.userPassword;
                                                    String ip = bankFront.serverIP;
                                                    String localPath = bankFront.bkTransFolder;
                                                    //共享文件夹下载路径
                                                    //路径格式smb://pub:fingard1!@10.60.44.98/数据库脚本/2.3.0/371-388.sql
                                                    if(StringHelper.isNullOrEmpty(userName)&&StringHelper.isNullOrEmpty(userPassword)){
                                                        filePath = "smb://"+ip+"/"+localPath+"/"+fileName;
                                                    }
                                                    filePath = "smb://"+userName+":"+userPassword+"@"+ip+"/"+localPath+"/"+fileName;
                                                    SmbFile smbFile = new SmbFile(filePath);
                                                    int length = smbFile.getContentLength();//得到文件的大小
                                                    byte buffer[] = new byte[length];
                                                    in = new SmbFileInputStream(smbFile); //建立smb文件输入流
                                                    //读取gz压缩文件的内容
                                                    inputStream = new GZIPInputStream(in);
                                                    sc = new Scanner(inputStream);
                                                    List<String> lines = new ArrayList();
                                                    while (sc.hasNextLine()) {
                                                        lines.add(sc.nextLine());
                                                    }
                                                    String ftpFileContent = lines.toString();
                                                    /*String ftpFileContent = FtpUtil.getTextFromFile(filePath, getCharset());*/
                                                    if (ftpFileContent.equals("")) {
                                                        tmpRetDetail.respCode = "-1";
                                                        tmpRetDetail.respInfo = "读取对账单文件失败!";
                                                    }
                                                    WriteBankLogStep3(ftpFileContent);
                                                    StringReader stringReader = new StringReader(ftpFileContent);
                                                    BufferedReader bufferedReader = new BufferedReader(stringReader);
                                                    String readLine = "";
                                                    while ((readLine = bufferedReader.readLine()) != null) {
                                                        String eachline = readLine.trim();
                                                        //TODO  由于文件的内容格式未知不知如何取值
                                                        String[] values = eachline.split("");//不知道以什么分割
                                                        if (values.length > 0) {
                                                            //TODO  给tmpRetDetail返回需要的对账的余额的值


                                                        }
                                                    }
                                                    bufferedReader.close();
                                                    sc.close();
                                                } catch (Exception e) {
                                                    e.printStackTrace();
                                                } finally {
                                                    if (in != null) {
                                                        in.close();
                                                    }
                                                    if (sc != null) {
                                                        sc.close();
                                                    }
                                                    if (inputStream != null) {
                                                        inputStream.close();
                                                    }
                                                }
                                            }
                                        } else {
                                            tmpRetDetail.respCode = "-1";
                                            tmpRetDetail.respInfo = tmprspmsg;
                                        }
                                    }
                                } else {
                                    tmpRetDetail.respCode = "-1";
                                    tmpRetDetail.respInfo = tmpStrRet[1];
                                }
                            } else {
                                tmpRetDetail.respCode = "-1";
                                tmpRetDetail.respInfo = tmpEachRspmsg;
                                if (StringHelper.isNullOrEmpty(tmpRetDetail.respInfo)) {
                                    tmpRetDetail.respInfo = tmpEachRspcod;
                                }
                            }
                        } else {
                            tmpRetDetail.respCode = "-1";
                            tmpRetDetail.respInfo = "status节点为空";
                        }
                        retAts.writeRetDetail(tmpRetDetail);
                    }
                } else {
                    retAts.writeRespCode("-1");
                    retAts.writeRespInfo(tmprspmsg);
                }
            } else {
                retAts.writeRespCode("-1");
                retAts.writeRespInfo(tmpSbMsg.toString());
            }
        } else {
            //模拟银行返回 只模拟返回到ATS  银行的无法模拟
                /*RetAtsBalCheckDetail tmpRetDetail = new RetAtsBalCheckDetail();
                tmpRetDetail.respCode = "0";
                tmpRetDetail.respInfo = "";
                tmpRetDetail.actNum = p_req7508.actNum;
                tmpRetDetail.statementNumber = p_req7508.reqHeader.transSeqID;//对账单编号
                tmpRetDetail.acctType = "2";//存款种类
                tmpRetDetail.actCur = "CNY";
                String dzFlag = "2";
                String atsFlag = "";
                if ("1".equals(dzFlag)) {
                    atsFlag = "2";
                } else if ("2".equals(dzFlag)) {
                    atsFlag = "3";
                } else {//默认（0）和未对账（3）
                    atsFlag = "1";
                }
                tmpRetDetail.dzFlag = atsFlag;
                tmpRetDetail.actName = "末账户";
                tmpRetDetail.actBal = "254.00";
                tmpRetDetail.amountIncurred = "456.00";
                retAts.writeRetDetail(tmpRetDetail);*/
            retAts.writeRespCode("-1");
            retAts.writeRespInfo(tmpStrRet[1]);
        }
    }
}
